<template>
  <el-container :style="{height: containerHeight + 'px'}">
    <el-aside
      style="padding: 10px 0 0 0;background-color: #fff;border-right: 1px solid #dfe6ec"
      width="13%"
    >
      <!-- 左侧部门菜单树 -->
      <el-tree
        ref="leftDepartmentTree"
        v-loading="treeLoading"
        style="font-size: 14px;"
        :data="departments"
        node-key="id"
        default-expand-all
        empty-text="暂无数据"
        :props="departmentsTreeProps"
        :show-checkbox="false"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <div slot-scope="{ node, data }" class="user-tree-node">
          <div>
            <span v-if="data.children.length === 0">
              <i class="el-icon-document" />
            </span>
            <span v-else @click.stop="changeIcon(data)">
              <!--              <svg-icon v-if="data.open" icon-class="add-s" />-->
              <i v-show="data.open" class="el-icon-circle-plus-outline" />
              <i v-show="!data.open" class="el-icon-remove-outline" />
              <!--              <svg-icon v-else icon-class="sub-s" />-->
            </span>
            <!-- 名称 -->
            <span style="margin-left: 3px">{{ node.label }}</span>
          </div>
        </div>
      </el-tree>
    </el-aside>
    <!-- 右侧用户列表数据 -->
    <el-main>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.username" style="width: 200px" placeholder="请输入用户名" />
          <el-input v-model="searchForm.realName" style="width: 200px;margin-left: 5px" placeholder="请输入真实姓名" />
          <el-input v-model="searchForm.phone" style="width: 200px;margin-left: 5px" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
          <el-button icon="el-icon-refresh-right" @click="onRefresh">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="openEditWindow">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        :style="{height: tableHeight + 'px'}"
        row-key="id"
        border
      >
        <el-table-column
          prop="realName"
          label="姓名"
          align="center"
          sortable
          width="120"
        />
        <el-table-column
          prop="username"
          label="用户名"
          sortable
          align="center"
          width="150"
        />
        <el-table-column
          prop="roleName"
          label="角色"
          align="center"
          sortable
          width="200"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.roleName">{{ scope.row.roleName }}</span>
            <span v-else style="color: red">未分配</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="departmentName"
          label="所属部门"
          align="center"
          sortable
          width="200"
        />
        <el-table-column
          prop="phone"
          label="电话"
          align="center"
          sortable
          width="200"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          align="center"
          sortable
          width="200"
        />
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit-outline" size="small" @click="edit(scope.row.id)">编辑
            </el-button>
            <el-button type="success" icon="el-icon-setting" size="small" @click="assignRole(scope.row)">分配角色
            </el-button>
            <el-button type="danger" icon="el-icon-close" size="small" @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="position: fixed;bottom: 0;padding-bottom: 20px">
        <el-pagination
          :current-page="searchForm.current"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="searchForm.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchForm.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <SystemDialog
        :title="userDialog.title"
        :visible="userDialog.visible"
        :width="userDialog.width"
        :height="userDialog.height"
        @onClose="onClose"
        @onConfirm="onConfirm"
      >
        <div slot="content">
          <el-form
            ref="editUserForm"
            :model="editUserForm"
            :rules="editUserRules"
            label-width="80px"
            :inline="true"
            size="small"
          >
            <el-form-item v-if="!editUserForm.id" label="用户名" prop="username">
              <el-input v-model="editUserForm.username" :disabled="typeof this.editUserForm.id !== 'undefined'" placeholder="请输入用户名" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item v-if="!editUserForm.id" label="密码" prop="password">
              <el-input v-model="editUserForm.password" type="password" placeholder="请输入密码" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="所属部门" prop="departmentName">
              <el-select
                v-model="editUserForm.departmentName"
                class="edit-user-input"
                filterable
                placeholder="请选择所属部门"
                @change="parentDepartmentChange"
              >
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="editUserForm.realName" placeholder="请输入姓名" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="editUserForm.phone" placeholder="请输入电话" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="editUserForm.nickName" placeholder="请输入昵称" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email" placeholder="请输入邮箱" class="edit-user-input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="editUserForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :action="uploadURL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="头像">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </SystemDialog>
    </el-main>
  </el-container>
</template>
<script>
import { getDepartmentList, getParentDepartment } from '@/api/department'
import { deleteUserById, getUserById, getUsers, saveUsers } from '@/api/user'
import SystemDialog from '@/components/system/SystemDialog'
import { uploadURL } from '@/api/upload'
import myconfirm from '@/utils/myconfirm'

export default {
  components: { SystemDialog },
  data() {
    return {
      uploadURL: uploadURL(),
      searchForm: {
        size: 10,
        current: 1
      },
      imgUrl: '',
      tableData: [],
      tableLoading: false,
      treeLoading: false,
      tableHeight: 0,
      containerHeight: 0, // 容器高度
      departments: [],
      departmentsTreeProps: {
        children: 'children',
        label: 'name'
      },
      userDialog: {
        title: '',
        visible: false,
        width: 590, // 窗口宽度
        height: 450 // 窗口高度
      },
      editUserForm: {
        gender: 1
      },
      editUserRules: {
        username: [{ required: true, trigger: 'change', message: '请输入用户名' }],
        password: [{ required: true, trigger: 'change', message: '请输入密码' }],
        departmentName: [{ required: true, trigger: 'change', message: '请选择所属部门' }],
        realName: [{ required: true, trigger: 'change', message: '请输入姓名' }],
        phone: [{ required: true, trigger: 'change', message: '请输入电话' }],
        gender: [{ required: true, trigger: 'change', message: '请选择性别' }]
      },
      departmentOptions: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 容器高度
      this.containerHeight = window.innerHeight - 90
      this.tableHeight = window.innerHeight - 230
    })
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.editUserForm.avatar = res.data
      this.imgUrl = this.editUserForm.avatar
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    parentDepartmentChange(val) {
      console.log(val)
      this.editUserForm.departmentId = val.id
      this.editUserForm.departmentName = val.name
    },
    getParentDepartment() {
      getParentDepartment().then(res => {
        this.departmentOptions = res.data
        this.departmentOptions.splice(0, 1)
      })
    },
    onConfirm() {
      this.$refs.editUserForm.validate(valid => {
        if (valid) {
          saveUsers(this.editUserForm).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message({
                showClose: true,
                message: res.msg,
                type: 'success'
              })
              this.clearEditWindow()
              this.getUserList()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    clearEditWindow() {
      this.userDialog.visible = false
      this.editUserForm = {
        gender: 1
      }
      this.imgUrl = ''
      this.$refs['editUserForm'].resetFields()
    },
    onClose() {
      this.clearEditWindow()
    },
    getUserList() {
      this.tableLoading = true
      getUsers(this.searchForm).then(res => {
        if (res.data.current > 1 && res.data.records.length <= 0) {
          this.searchForm.current = res.data.current - 1
          this.getUserList()
        } else {
          this.tableData = res.data.records
          this.searchForm.total = res.data.total
          this.tableLoading = false
        }
      })
    },
    openEditWindow() {
      this.getParentDepartment()
      this.userDialog.title = '编辑'
      this.userDialog.visible = true
    },
    onRefresh() {
      this.searchForm.username = ''
      this.searchForm.realName = ''
      this.searchForm.phone = ''
      this.getUserList()
    },
    onSearch() {
      this.getUserList()
    },
    assignRole(row) {

    },
    edit(id) {
      getUserById(id).then(res => {
        this.editUserForm = res.data
        this.imgUrl = this.editUserForm.avatar
        this.openEditWindow()
      })
    },
    async remove(id) {
      const result = await myconfirm('确定删除吗')
      if (result) {
        deleteUserById(id).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功')
            this.getUserList()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    getDepartmentList() {
      this.treeLoading = true
      getDepartmentList().then(res => {
        this.departments = res.data
        this.$nextTick(() => {
          const firstNode = document.querySelector('.el-tree-node')
          firstNode.click()
          this.treeLoading = false
        })
      })
    },
    handleNodeClick(data) {
      this.searchForm.departmentId = data.id
      this.getUserList()
    },
    changeIcon(data) {
      data.open = !data.open
      this.$refs.leftDepartmentTree.store.nodesMap[data.id].expanded = !data.open
    },
    handleSizeChange(size) {
      this.searchForm.size = size
      this.getUserList()
    },
    handleCurrentChange(current) {
      this.searchForm.current = current
      this.getUserList()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.edit-user-input {
  width: 180px;
}
::v-deep .el-tree {
  .el-tree-node {
    position: relative;
    padding-left: 10px;
  }

  .el-tree-node__children {
    padding-left: 20px;
  }

  .el-tree-node :last-child:before {
    height: 40px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node:before,
  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .tree :first-child .el-tree-node:before {
    border-left: none;
  }

  .el-tree-node:before {
    border-left: 1px dotted #d9d9d9;
    bottom: 0px;
    height: 100%;
    top: -25px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dotted #d9d9d9;
    height: 20px;
    top: 14px;
    width: 24px;
  }

  .el-tree-node__expand-icon.is-leaf {
    width: 8px;
  }

  .el-tree-node__content > el-tree-node__expand-icon {
    display: none;
  }

  .el-tree-node__content {
    line-height: 30px;
    height: 30px;
    padding-left: 10px !important;
  }
}

::v-deep .el-tree > div {
  &::before {
    display: none;
  }

  &::after {
    display: none;
  }
}
</style>

